<?php

namespace Yjius\openapi\bilibili;

use Yjius\common\CurlHelper;

/**
 * B站扫描登录-暂无账号调试-使用时注意
 * Class BilibiliOauth
 * @package Yjius\openapi\bilibili
 * @date  2022/7/27 10:23
 */
class BilibiliOauth
{
    //应用参数
    private $client_id = null;
    private $client_secret = null;
    private $redirect_uri = null;

    //最外层初始化时，YII_ENV 可以选择不同的应用
    public function __construct($config = [])
    {
        //裁入配置
        $this->client_id = $config['client_id'] ?: '';
        $this->client_secret = $config['client_secret'] ?: '';
        $this->redirect_uri = $config['redirect_uri'] ?: '';
        if (empty($this->client_id) || empty($this->client_secret) || empty($this->redirect_uri)) {
            throw new \Exception("载入配置错误，请检查参数是否正确");
        }
    }

    /**
     * 返回【第一步：请求CODE】的url
     */
    public function getCodeUrl($state = '')
    {
        $redirectUri = urlencode($this->redirect_uri);
        $url = " https://passport.bilibili.com/register/pc_oauth2.html#/?client_id={$this->client_id}
        &response_type=code&state={$state}&return_url={$redirectUri}";
        return $url;
    }

    /**
     * 第二步：通过code获取access_token
     * @param $code
     * @return bool|mixed|string
     */
    public function getAccessToken($code)
    {
        $params = [
            'code' => $code,
            'grant_type' => 'authorize_code',
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret,
        ];
        $url = 'https://api.bilibili.com/x/account-oauth2/v1/token';
        $res = CurlHelper::httpRequest($url, [], 'POST', $params);
        return json_decode($res, true);
    }

    /**
     * 第三步：获取用户信息
     * @param string $token
     * @param string $media_id
     * @return array
     */
    public function getLoginInfo($accessToken)
    {
        $url = 'http://member.bilibili.com/arcopen/fn/user/account/info';
        $params['client_id'] = $this->client_id;
        $params['access_token'] = $accessToken;
        $res = CurlHelper::httpRequest($url, [], 'GET', $params);
        return json_decode($res, true);
    }

}